package _org;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import mozzilla.RenderTextHTML;
import mozzilla.RenderTextXML;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import adobe.StandardOutViewer;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("main > .");

		RenderDevice device = new RenderDevice(new RenderTextHTML(), new RenderTextXML());
		DagElementFactory factory = new DagElementFactory(device);
		// not really object oriented but here there is not a sparing-time parser issue 
		// factory is called inside makedag function
		DagElement root = test_makedag(factory);
		DumbBrowser browser = new DumbBrowser(new StandardOutViewer());
		browser.navigate(root);
	}

	private static DagElement test_makedag(DagElementFactory factory) {
		NodeList nodes = parse("xmltest.xml");
		return makedag(nodes, factory);
	}

	private static DagElement makedag(NodeList nodeLst, DagElementFactory factory) {
		System.out.println("makedag > .");
		
		DagElement root = factory.getRoot();
		// ok. now traverse all xml document, we know xml structure of xmltest.xml:
		// childs are employee list
		// each employee contains fist name
		// and stop.
		for (int s = 0; s < nodeLst.getLength(); s++) {
			Node fstNode = nodeLst.item(s);
			DagElement employee = root.addChild( factory.getElement("XML", "EMPLOYEE", "") );
			//System.out.println("get <employee>");
			if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
				Element fstElmnt = (Element) fstNode;
				NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
				Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
				NodeList fstNm = fstNmElmnt.getChildNodes();
				//System.out.println("get <name>");
				employee.addChild(factory.getElement("XML", "NAME", fstNm.item(0).getNodeValue()));
			} 
		}
		return root;
	}

	private static NodeList parse(String namefile) {
		System.out.println("parse > .");
		// parse xml example from: http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
		try {
			File file = new File(namefile);
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document doc = db.parse(file);
			doc.getDocumentElement().normalize();
			NodeList nodeLst = doc.getElementsByTagName("employee");
			return nodeLst;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
